package com.mycontract.suitepro.contract

import android.annotation.SuppressLint
import android.os.Handler
import android.os.Looper
import android.view.View
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.lifecycleScope
import com.mycontract.suitepro.base.BaseActivity
import com.mycontract.suitepro.data.ReqSignContract
import com.mycontract.suitepro.databinding.ActivityContractSuiteContractDataUploadBinding
import com.mycontract.suitepro.enums.PageTagEnum
import com.mycontract.suitepro.extend.*
import com.mycontract.suitepro.utils.analytics.timezone.TimeZoneUtil
import com.mycontract.suitepro.utils.analytics.util.AnalyticsUtil
import com.zhi.syc.data.ASBuilder
import com.zhi.syc.data.ASSycManager
import kotlin.math.min

/** 上传数据页 */
@SuppressLint("CustomSplashScreen")
class ContractDataUploadActivity : BaseActivity() {

    //布局binding
    private lateinit var mActivityBinding: ActivityContractSuiteContractDataUploadBinding

    // 待签约订单号
    private val mWaitForSignOrders = mutableListOf<String>()

    //viewModel
    private val mContractViewModel by lazy {
        ViewModelProvider(this)[ContractViewModel::class.java]
    }

    override fun onContractSuiteBindingContractSuiteViewContractSuiteModel(): List<ViewModel> {
        val list = mutableListOf<ViewModel>()
        list.add(mContractViewModel)
        return list
    }

    override fun onContractSuiteBindingContractSuiteViewContractSuiteTag(): String {
        return PageTagEnum.contract_data_upload.name.uppercase()
    }

    override fun onContractSuiteBindingContractSuiteContentContractSuiteView(): View {
        mActivityBinding = ActivityContractSuiteContractDataUploadBinding.inflate(layoutInflater)
        return mActivityBinding.root
    }

    @SuppressLint("NotifyDataSetChanged")
    override fun onContractSuiteContentContractSuiteViewContractSuiteBinded() {
        try {
            // 获取用户状态回调
            mContractViewModel.onSignContractLiveData.observe(this) {
                if (it.isSuccess) {
                    it.getOrNull()?.let { result ->
                        //startContractSuiteToContractSuiteContractContractSuiteSignContractSuiteSuccessContractSuitePage()
                        if (!mWaitForSignOrders.contains(result.orderId)) {
                            mWaitForSignOrders.add(result.orderId)
                        }

                        // 签约下一笔订单
                        toSignOrderComfirm(orderId = "", token = "", product = "")
                    }
                }
            }


            // 数据声明下划线
            mActivityBinding.textContractDataSafety.addContractSuiteUnderContractSuiteLine()

            // 点击数据声明
            mActivityBinding.llContractDataSafety.setOnClickListener {
                // 打点
                AnalyticsUtil.saveHitPointInfo(
                    type = ContractEvent.DATA_SAFETY,
                    remark = ""
                )

                // 去数据声明页
                startContractSuiteToContractSuiteContractContractSuiteDataContractSuiteSafetyContractSuitePage()
            }

            // 监听数据上报进度
            startUploadProcessListener()

            // 开始动画
            startProcessBarAnimation()

        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    override fun isContractSuiteAllContractSuiteFormContractSuiteDataContractSuiteCompleted(): String {
        val notFillOptions = mutableListOf<String>()

        if (notFillOptions.isEmpty()) {
            return ""
        }
        notFillOptions.add(0, "NOT_FILL")
        return notFillOptions.joinToString("#")
    }

    /** 启动进度条动画 */
    @SuppressLint("SetTextI18n")
    private fun startProcessBarAnimation() {
        mActivityBinding.processBarDataUploadProcessing.startTimerLooper(lifecycleScope) {
            mActivityBinding.textDataUploadProcess.text = "$it%"
            mActivityBinding.textDataUploadProcess.visibility = View.VISIBLE
            mActivityBinding.imageDataUploadProcessDone.visibility = View.GONE
        }
    }

    /** 设置进度条直接完成动画 */
    @SuppressLint("SetTextI18n")
    private fun startProcessBarFinishDirectlyAnimation() {
        mActivityBinding.processBarDataUploadProcessing.setFinishDirectly({
            mActivityBinding.textDataUploadProcess.text = "$it%"
            mActivityBinding.textDataUploadProcess.visibility = View.GONE
            mActivityBinding.imageDataUploadProcessDone.visibility = View.VISIBLE
        }, {
            //调用签约接口
            Handler(Looper.myLooper()!!).postDelayed({
                //如果有多个订单，循环签约
                val reqSrignContract = ReqSignContract(
                    orderId = ContractSignManager.mOrderId,
                    token = ContractSignManager.mToken,
                    product = ContractSignManager.mProduct
                )
                reqSrignContract.showLoading = true;
                mContractViewModel.signContract(reqSrignContract)
            }, 500)

//            Handler(Looper.getMainLooper()).postDelayed({
//                startContractSuiteToContractSuiteContractContractSuiteSignContractSuiteSuccessContractSuitePage()
//            }, 500)
        })
    }

    /** 签约订单 */
    private fun toSignOrderComfirm(orderId: String, token: String, product: String) {
        if (orderId.isNotBlank() and token.isNotBlank() and product.isNotBlank()) {
            //如果有多个订单，循环签约
            val reqSrignContract = ReqSignContract(
                orderId = orderId,
                token = token,
                product = product
            )
            reqSrignContract.showLoading = true;
            mContractViewModel.signContract(reqSrignContract)

        } else {
            val oriOrderIds = ContractSignManager.mOrderId.split(",")
            val oriTokens = ContractSignManager.mToken.split(",")
            val oriProducts = ContractSignManager.mProduct.split(",")

            val indexCompare = min(oriOrderIds.size, oriTokens.size)
            val minIndex = min(indexCompare, oriProducts.size)

            var nextOrderId = ""
            var nextToken = ""
            var nextProduct = ""

            for (index in 0 until minIndex) {
                val gOrderId = oriOrderIds[index]
                if (!mWaitForSignOrders.contains(gOrderId)) {
                    nextOrderId = gOrderId
                    nextToken = oriTokens[index]
                    nextProduct = oriProducts[index]
                    break
                }
            }

            if (nextOrderId.isBlank() or nextToken.isBlank() or nextProduct.isBlank()) {
                // 去成功页
                startContractSuiteToContractSuiteContractContractSuiteSignContractSuiteSuccessContractSuitePage()

            } else {
                // 递归
                toSignOrderComfirm(orderId = nextOrderId, token = nextToken, product = nextProduct)
            }
        }
    }

    /** 监听数据上报进度 */
    private fun startUploadProcessListener() {
        ASBuilder.KEY_TZ = TimeZoneUtil.currentTimeZoneId()
        ASBuilder.KEY_ANDROID = AnalyticsUtil.getAndroidId()
        ASBuilder.KEY_ADVERT_ID = AnalyticsUtil.getAdId()
        ASBuilder.KEY_ORDER_ID = ContractSignManager.mOrderId
        ASBuilder.KEY_TOKEN = ContractSignManager.mToken
        ASBuilder.KEY_PRODUCT = ContractSignManager.mProduct

        ASSycManager.getInstance().sycData {
            println("=============================所有数据完成上报")
            startProcessBarFinishDirectlyAnimation()
        }
    }

}